/**
 * 
 */
package io.dora.protocol;

import io.dora.conf.ProviderConfig;
import io.dora.conf.ServiceURL;
import io.dora.remoting.ConsumerClient;
import io.dora.remoting.NettyProviderServer;
import io.dora.remoting.ProviderServer;
import io.dora.utils.Utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 默认协议实现
 * 
 * @author zhaohongbo
 *
 */
public class DoraProtocol extends AbstractProtocol {
	
	private Logger logger = LoggerFactory.getLogger(DoraProtocol.class);
	
	/** 服务端口 */
	private int servicePort = Utils.getLocalPort();
	
	/** 服务提供者服务器 */
	private ProviderServer providerServer;
	
	/** Provider容器 */
	private Map<String, Object> serviceMap = new ConcurrentHashMap<String, Object>();
	
	/** Consumer容器 */
	private Map<String, ConsumerClient> consumerClientMap = new ConcurrentHashMap<String, ConsumerClient>();

	@Override
	public <T> void export(ProviderConfig<T> serviceProvider) {
		serviceMap.put(serviceProvider.getServiceKey(), serviceProvider.getRef());
		start();
		serviceProvider.getRegistry().register(new ServiceURL(Utils.getIp(), this.getServicePort(), serviceProvider.getServiceKey()));
	}

	@Override
	public void shutdown() {
		providerServer.stop();
	}
	
	private void start() {
		if (providerServer == null) {
			providerServer = new NettyProviderServer(this);
			providerServer.load(serviceMap);
			providerServer.start();
			logger.info("Server started.");
		}
	}

	@Override
	public int getServicePort() {
		return servicePort;
	}

	@Override
	public Map<String, ConsumerClient> getConsumerClientMap() {
		return consumerClientMap;
	}

	public void setConsumerClientMap(Map<String, ConsumerClient> consumerClientMap) {
		this.consumerClientMap = consumerClientMap;
	}
}
